import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://203.57.5.167:8000/',
  // url = base url + request url
  timeout: 7000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer' + ' ' + getToken();
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    // console.log(res);
    if (res.code !== 0) {
      if (res.text == '顶级节点') {
        return res;
      }
      if (res.isApp == true) {
        return res;
      }
      if (res.code == -1) {
        return res
      }
      // Message({
      //   message: res.msg || 'Error11',
      //   type: 'error',
      //   duration: 5 * 1000
      // })
      // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      //   // to re-login
      //   MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
      //     confirmButtonText: 'Re-Login',
      //     cancelButtonText: 'Cancel',
      //     type: 'warning'
      //   }).then(() => {
      //     store.dispatch('user/resetToken').then(() => {
      //       location.reload()
      //     })
      //   })
      // };
      // return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    //// console.log('err11' + error) // for debug
    // if (error.message=='timeout of 5000ms exceeded'){
    //   Message({
    //     message: '登录超时',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    // }else{
    //   Message({
    //     message: error.message,
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    // }
    // return Promise.reject(error + '123')
  }
)

export default service
